import { listNovelAllChapterUsingGet } from "@/services/novel-web/chapterController";
import { getNovelInfoUsingGet } from "@/services/novel-web/novelController";
import { MessageError, scrollToTop } from "@/utils/commonUtils";
import { PageContainer } from "@ant-design/pro-components";
import { history, useParams } from "@umijs/max";
import { Button, Card, Col, Row, Typography } from "antd";
import { Content } from "antd/es/layout/layout";
import { Divider } from "antd/lib";
import { useEffect, useRef, useState } from "react";
import ReactQuill from "react-quill";
import './index.less';
const {Paragraph,Title,Text} = Typography;

const NovelRead: React.FC = ()=>{

  // url :id , :chapterId
  const {id:novelId,chapterId} = useParams<{id: string,chapterId: string}>();
  
  // novel
  const [info,setInfo] = useState<API.NovelInfo>();

  // chapters
  const [chapters,setChapters] = useState<API.ChapterVO[]>();
  const [curIndex,setCurIndex] = useState<number>(-1);

  // text
  const [text, setText] = useState('');

  // reader
  const readerRef = useRef<ReactQuill>(null);

  // btns
  const [dispre,setDispre] = useState(false);
  const [disnext,setDisnext] = useState(false);


  const loadNovelInfo = async (id:string) => {
    try {
      const resp = await getNovelInfoUsingGet({
        id: Number(id),
      });
      setInfo(resp.data);

    } catch (error: any) {
      MessageError(error);
    }
  };

  const loadChapters = async (id:string)=>{
    try {
      const resp = await listNovelAllChapterUsingGet({
        novelId: Number(id),
      });

      setChapters(resp.data);
      
    } catch(error:any) {
      MessageError(error);
    }
  };

  const loadText = async (url:string) =>{
    try {
      // TODO: attention: fetch
      const resp = await fetch(url);
      if(!resp.ok) {
        const error: any = new Error("get file error");
        error.name = 'respError';
        error.info = { 
          code: resp.status,
          data: null,
          message:"get file error"
        };
        throw error;
      }
      const t = await resp.text();
      setText(t);
      // setLoading(false);

    } catch (error) {
      MessageError(error);
      // setLoading(false);
    }
  };


  useEffect(()=>{
    if(novelId == '0') {
      history.push("/");
    }
    loadNovelInfo(novelId ?? '');
    loadChapters(novelId ?? '');
  },[])

// loadChapters(),chapterId => setCurIndex(chapterId) => loadText(chapters[curIndex]) => quill.setText(...)
  useEffect(()=>{
    if(chapters && chapters?.length >0 && chapterId) {
      const found =  chapters.findIndex(value => value.id == Number(chapterId));
      setCurIndex(found);
    }
  },[chapters,chapterId])

  useEffect(()=>{
    // console.debug(curIndex);
    // console.debug(chapters?.at(curIndex));
    if(curIndex != -1 ) {
      const cur = chapters?.at(curIndex);
      if(cur && cur.res){
        loadText(cur.res);
      }
    }

    // url
    window.history.pushState('','',`/novel/${novelId}/${chapters?.at(curIndex)?.id}`)
  
    // btns disable
    if(curIndex == 0) {
      setDispre(true);
    } else {
      setDispre(false);
    }
    if (chapters && curIndex == (chapters?.length -1)) {
      setDisnext(true);
    } else {
      setDisnext(false);
    }
    scrollToTop();
  },[curIndex]);

  useEffect(()=>{
    const quill = readerRef.current?.getEditor();
    if(quill) {
      quill.setText(text);
    }
  },[text]);
  
 
  // pre-btn
  const handlePrevChapter = () =>{
    setCurIndex(curIndex-1);
  };
  // next-btn
  const handleNextChapter = () =>{
    setCurIndex(curIndex + 1);
    
  };

  

  
  // const handleToTop = ()=> {
  //   window.scrollTo({
  //     top:0,
  //     behavior: "smooth"
  //   });
  // }

  return (
    <PageContainer
    header={{
      ghost: true,
      breadcrumb:{
        items: [
          {
            href: '/welcome',
            title: '首页',
          },
          {
            href: `/novel/${novelId}`,
            title: info?.name,
          },
        ]
      },
    }}
    ><div className='page'>
      <Content className='content'>
        <Row justify={"center"}>
          {/* 左侧按钮 */}
          {/* <Col className='leftBar' >
            <Button 
              className='floatBtn'
              icon={<UnorderedListOutlined />} 
              size="large" 
              onClick={handlePrevChapter} 
            />
            <Button 
              icon={<FileAddOutlined />} 
              className='floatBtn'
              size="large" 
              onClick={handlePrevChapter} 
            />
            <Button 
              icon={<BookOutlined />} 
              className='floatBtn'
              size="large" 
              onClick={handlePrevChapter} 
            />
          </Col> */}

          {/* 文章内容 */}
          <Col>
          <Card className='article-card'>
            <Title className="title" level={4}>
              {chapters?.at(curIndex)?.title}
            </Title>
            <Divider/>

            {/* {text.split('\n').map((line, index) => (
              <p key={index}>{line}</p>
            ))} */}
            <ReactQuill 
              className="custom-quill-editor"
              readOnly={true}
              ref={readerRef}
              modules={{
                toolbar: false,
              }}
            />
            
            <Row align={"middle"} justify={"center"} >
              <Button style={{margin: 8}} 
                disabled={dispre}
                onClick={handlePrevChapter}
              >上一章</Button>
              <Button style={{margin: 8}}
                href={`/novel/${novelId}/chapters`}
              >目录</Button>
              <Button style={{margin: 8}} 
                disabled={disnext}
                onClick={handleNextChapter}
              >下一章</Button>
            </Row>  
          </Card>
          </Col>

          {/* 右侧按钮 */}
          {/* <Col className='rightBar'>
            <Button 
              icon={<RightOutlined />} 
              className='floatBtn'
              size="large" 
              onClick={handleNextChapter} 
            />
            <Button 
              className='floatBtn'
              icon={<LeftOutlined />} 
              size="large" 
              onClick={handlePrevChapter} 
            />
            <Button 
              icon={<VerticalAlignTopOutlined />} 
              className='floatBtn'
              size="large" 
              onClick={handleToTop} 
            />
          </Col> */}

          
        </Row>
        
      </Content>
      
    </div>
    </PageContainer>
  );
};



export default NovelRead;


